<?php
class Questionnaire {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 创建新问卷
     */
    public function create(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            // 验证必填字段
            if (empty($input['title'])) {
                throw new Exception("问卷标题不能为空", 400);
            }

            $stmt = $this->conn->prepare("
                INSERT INTO questionnaires (
                    user_id, title, description, status, created_at, updated_at
                ) VALUES (
                    :user_id, :title, :description, 'draft', NOW(), NOW()
                )
            ");

            $stmt->execute([
                ':user_id' => $userId,
                ':title' => $input['title'],
                ':description' => $input['description'] ?? ''
            ]);

            $questionnaireId = $this->conn->lastInsertId();

            echo json_encode([
                'code' => 200,
                'msg' => '问卷创建成功',
                'data' => [
                    'id' => $questionnaireId
                ]
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 更新问卷信息
     */
    public function update(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            if (empty($input['id'])) {
                throw new Exception("缺少问卷ID", 400);
            }

            // 检查问卷是否存在且属于当前用户
            $questionnaire = $this->getQuestionnaire($input['id'], $userId);
            if (!$questionnaire) {
                throw new Exception("问卷不存在或无权操作", 404);
            }

            // 构建更新字段
            $updateFields = ["updated_at = NOW()"];
            $params = [':id' => $input['id']];

            // 可更新字段
            $allowedFields = ['title', 'description'];
            foreach ($allowedFields as $field) {
                if (isset($input[$field])) {
                    $updateFields[] = "{$field} = :{$field}";
                    $params[":{$field}"] = $input[$field];
                }
            }

            if (count($updateFields) <= 1) {
                throw new Exception("没有可更新的字段", 400);
            }

            $sql = "UPDATE questionnaires SET " . implode(', ', $updateFields) . " 
                    WHERE id = :id AND user_id = :user_id";
            $params[':user_id'] = $userId;
            
            $stmt = $this->conn->prepare($sql);
            $stmt->execute($params);

            echo json_encode([
                'code' => 200,
                'msg' => '问卷更新成功'
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 获取问卷列表
     */
    public function list(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取分页参数
            $page = max(1, intval($_GET['page'] ?? 1));
            $pageSize = min(50, max(1, intval($_GET['pageSize'] ?? 20)));
            $offset = ($page - 1) * $pageSize;

            // 构建查询条件
            $where = ["user_id = :user_id", "is_template = 0"];
            $params = [':user_id' => $userId];
            
            // 添加筛选条件
            if (!empty($_GET['status'])) {
                $where[] = "status = :status";
                $params[':status'] = $_GET['status'];
            }

            if (!empty($_GET['keyword'])) {
                $where[] = "(title LIKE :keyword OR description LIKE :keyword)";
                $params[':keyword'] = '%' . $_GET['keyword'] . '%';
            }

            $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

            // 查询总数
            $countStmt = $this->conn->prepare("
                SELECT COUNT(*) FROM questionnaires {$whereClause}
            ");
            $countStmt->execute($params);
            $total = (int)$countStmt->fetchColumn();

            // 查询数据
            $query = "
                SELECT 
                    id, title, description, status, 
                    created_at, updated_at,
                    (SELECT COUNT(*) FROM answers WHERE questionnaire_id = questionnaires.id) as answer_count
                FROM questionnaires
                {$whereClause}
                ORDER BY updated_at DESC
                LIMIT :offset, :limit
            ";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            $stmt->execute();
            $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 返回列表数据
            echo json_encode([
                'code' => 200,
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'total' => $total,
                        'page' => $page,
                        'pageSize' => $pageSize,
                        'totalPages' => ceil($total / $pageSize)
                    ]
                ]
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 获取问卷详情
     */
    public function detail(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_GET['id'])) {
                throw new Exception("缺少问卷ID参数", 400);
            }

            $questionnaireId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
            if ($questionnaireId === false || $questionnaireId <= 0) {
                throw new Exception("问卷ID必须是正整数", 400);
            }

            // 查询问卷基本信息
            $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
            if (!$questionnaire) {
                throw new Exception("问卷不存在或无权查看", 404);
            }

            // 查询问题列表
            $stmt = $this->conn->prepare("
                SELECT 
                    id, type, content, is_required, sort_order, options, tips, is_date,  is_name
                FROM questions
                WHERE questionnaire_id = :questionnaire_id
                ORDER BY sort_order ASC
            ");
            $stmt->execute([':questionnaire_id' => $questionnaireId]);
            $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 格式化选项
            foreach ($questions as &$question) {
                if ($question['type'] === 'choice' && $question['options']) {
                    $question['options'] = json_decode($question['options'], true);
                }
            }

            // 返回结果
            echo json_encode([
                'code' => 200,
                'data' => [
                    'questionnaire' => $questionnaire,
                    'questions' => $questions
                ]
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }
  /**
 * 获取问卷详情(无权限)
 */
public function detailPublic(): void {
    try {
        if (empty($_GET['id'])) {
            throw new Exception("缺少问卷ID参数", 400);
        }

        $questionnaireId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
        if ($questionnaireId === false || $questionnaireId <= 0) {
            throw new Exception("问卷ID必须是正整数", 400);
        }

        // 查询问卷基本信息（无需用户权限，只检查是否已发布）
        $stmt = $this->conn->prepare("
            SELECT 
                id, title, description, status, 
                created_at, updated_at,
                (SELECT COUNT(*) FROM answers WHERE questionnaire_id = :id) as answer_count
            FROM questionnaires
            WHERE id = :id AND status = 'published'
            LIMIT 1
        ");
        $stmt->execute([':id' => $questionnaireId]);
        $questionnaire = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$questionnaire) {
            throw new Exception("问卷不存在或未发布", 404);
        }

        // 查询问题列表
        $stmt = $this->conn->prepare("
            SELECT 
                id, type, content, is_required, sort_order, options, tips, is_date,  is_name
            FROM questions
            WHERE questionnaire_id = :questionnaire_id
            ORDER BY sort_order ASC
        ");
        $stmt->execute([':questionnaire_id' => $questionnaireId]);
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 格式化选项
        foreach ($questions as &$question) {
            if ($question['options']) {
                $question['options'] = json_decode($question['options'], true);
            }
            
            // 为textgroup类型设置默认值
            if ($question['type'] === 'textgroup' && empty($question['options'])) {
                $question['options'] = [];
            }
        }

        // 返回结果
        echo json_encode([
            'code' => 200,
            'data' => [
                'questionnaire' => $questionnaire,
                'questions' => $questions
            ]
        ]);

    } catch (Exception $e) {
        throw $e;
    }
}
    /**
     * 发布问卷
     */
   /**
 * 发布问卷（POST方法）
 */
public function publish(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if ($input === null) {
            throw new Exception("无效的JSON数据", 400);
        }

        if (empty($input['id'])) {
            throw new Exception("缺少问卷ID参数", 400);
        }

        $questionnaireId = filter_var($input['id'], FILTER_VALIDATE_INT);
        if ($questionnaireId === false || $questionnaireId <= 0) {
            throw new Exception("问卷ID必须是正整数", 400);
        }

        // 检查问卷是否存在且属于当前用户
        $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
        if (!$questionnaire) {
            throw new Exception("问卷不存在或无权操作", 404);
        }

        // 检查问卷是否有问题
        $stmt = $this->conn->prepare("
            SELECT COUNT(*) FROM questions 
            WHERE questionnaire_id = :questionnaire_id
        ");
        $stmt->execute([':questionnaire_id' => $questionnaireId]);
        $questionCount = (int)$stmt->fetchColumn();

        if ($questionCount === 0) {
            throw new Exception("问卷必须至少有一个问题才能发布", 400);
        }

        // 更新状态为已发布
        $stmt = $this->conn->prepare("
            UPDATE questionnaires 
            SET status = 'published', updated_at = NOW()
            WHERE id = :id AND user_id = :user_id
        ");
        $stmt->execute([
            ':id' => $questionnaireId,
            ':user_id' => $userId
        ]);

        echo json_encode([
            'code' => 200,
            'msg' => '问卷已发布'
        ]);

    } catch (Exception $e) {
        throw $e;
    }
}

  /**
 * 关闭问卷（POST方法）
 */
public function close(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if ($input === null) {
            throw new Exception("无效的JSON数据", 400);
        }

        if (empty($input['id'])) {
            throw new Exception("缺少问卷ID参数", 400);
        }

        $questionnaireId = filter_var($input['id'], FILTER_VALIDATE_INT);
        if ($questionnaireId === false || $questionnaireId <= 0) {
            throw new Exception("问卷ID必须是正整数", 400);
        }

        // 检查问卷是否存在且属于当前用户
        $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
        if (!$questionnaire) {
            throw new Exception("问卷不存在或无权操作", 404);
        }

        // 检查问卷状态是否为已发布
        if ($questionnaire['status'] !== 'published') {
            throw new Exception("只有已发布的问卷才能关闭", 400);
        }

        // 更新状态为已关闭
        $stmt = $this->conn->prepare("
            UPDATE questionnaires 
            SET status = 'closed', updated_at = NOW()
            WHERE id = :id AND user_id = :user_id
        ");
        $stmt->execute([
            ':id' => $questionnaireId,
            ':user_id' => $userId
        ]);

        echo json_encode([
            'code' => 200,
            'msg' => '问卷已关闭'
        ]);

    } catch (Exception $e) {
        throw $e;
    }
}
    /**
     * 删除问卷
     */
    public function delete(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            if (empty($input['id'])) {
                throw new Exception("缺少问卷ID", 400);
            }

            $questionnaireId = $input['id'];

            // 检查问卷是否存在且属于当前用户
            $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
            if (!$questionnaire) {
                throw new Exception("问卷不存在或无权操作", 404);
            }

            // 开始事务
            $this->conn->beginTransaction();

            try {
                // 删除问题
                $stmt = $this->conn->prepare("
                    DELETE FROM questions 
                    WHERE questionnaire_id = :questionnaire_id
                ");
                $stmt->execute([':questionnaire_id' => $questionnaireId]);

                // 删除问卷
                $stmt = $this->conn->prepare("
                    DELETE FROM questionnaires 
                    WHERE id = :id AND user_id = :user_id
                ");
                $stmt->execute([
                    ':id' => $questionnaireId,
                    ':user_id' => $userId
                ]);

                $this->conn->commit();

                echo json_encode([
                    'code' => 200,
                    'msg' => '问卷删除成功'
                ]);

            } catch (Exception $e) {
                $this->conn->rollBack();
                throw new Exception("删除问卷失败: " . $e->getMessage(), 500);
            }

        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 获取公共模板列表
     */
    public function templates(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            $stmt = $this->conn->prepare("
                SELECT 
                    id, title, description, 
                    (SELECT COUNT(*) FROM questions WHERE questionnaire_id = questionnaires.id) as question_count
                FROM questionnaires
                WHERE is_template = 1
                ORDER BY id DESC
            ");
            $stmt->execute();
            $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode([
                'code' => 200,
                'data' => $templates
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 使用模板创建问卷
     */
    /**
 * 使用模板创建问卷或复制到现有问卷
 */
public function useTemplate(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if ($input === null) {
            throw new Exception("无效的JSON数据", 400);
        }

        if (empty($input['t_id'])) {
            throw new Exception("缺少模板ID参数", 400);
        }

        $templateId = filter_var($input['t_id'], FILTER_VALIDATE_INT);
        if ($templateId === false || $templateId <= 0) {
            throw new Exception("模板ID必须是正整数", 400);
        }

        // 检查模板是否存在
        $stmt = $this->conn->prepare("
            SELECT id, title, description 
            FROM questionnaires 
            WHERE id = :id AND is_template = 1
            LIMIT 1
        ");
        $stmt->execute([':id' => $templateId]);
        $template = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$template) {
            throw new Exception("模板不存在", 404);
        }

        // 开始事务
        $this->conn->beginTransaction();

        try {
            if (empty($input['q_id'])) {
                // 模式1: 创建新问卷
                $stmt = $this->conn->prepare("
                    INSERT INTO questionnaires (
                        user_id, title, description, status, is_template, created_at, updated_at
                    ) VALUES (
                        :user_id, :title, :description, 'draft', 0, NOW(), NOW()
                    )
                ");
                $stmt->execute([
                    ':user_id' => $userId,
                    ':title' => $template['title'] . ' (副本)',
                    ':description' => $template['description']
                ]);
                $newQuestionnaireId = $this->conn->lastInsertId();
            } else {
                // 模式2: 复制到现有问卷
                $questionnaireId = filter_var($input['q_id'], FILTER_VALIDATE_INT);
                if ($questionnaireId === false || $questionnaireId <= 0) {
                    throw new Exception("问卷ID必须是正整数", 400);
                }

                // 检查问卷是否存在且属于当前用户
                $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
                if (!$questionnaire) {
                    throw new Exception("问卷不存在或无权操作", 404);
                }

                // 先删除现有问题
                $stmt = $this->conn->prepare("
                    DELETE FROM questions 
                    WHERE questionnaire_id = :questionnaire_id
                ");
                $stmt->execute([':questionnaire_id' => $questionnaireId]);

                $newQuestionnaireId = $questionnaireId;
            }

            // 复制问题
            $stmt = $this->conn->prepare("
                INSERT INTO questions (
                    questionnaire_id, type, content, is_required, sort_order, options, created_at
                )
                SELECT 
                    :new_questionnaire_id, type, content, is_required, sort_order, options, NOW()
                FROM questions
                WHERE questionnaire_id = :template_id
            ");
            $stmt->execute([
                ':new_questionnaire_id' => $newQuestionnaireId,
                ':template_id' => $templateId
            ]);

            $this->conn->commit();

            echo json_encode([
                'code' => 200,
                'msg' => '模板使用成功',
                'data' => [
                    'id' => $newQuestionnaireId
                ]
            ]);

        } catch (Exception $e) {
            $this->conn->rollBack();
            throw new Exception("使用模板失败: " . $e->getMessage(), 500);
        }

    } catch (Exception $e) {
        throw $e;
    }
}

    /**
     * 获取问卷回答统计
     */
    public function answers(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_GET['id'])) {
                throw new Exception("缺少问卷ID参数", 400);
            }

            $questionnaireId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
            if ($questionnaireId === false || $questionnaireId <= 0) {
                throw new Exception("问卷ID必须是正整数", 400);
            }

            // 检查问卷是否存在且属于当前用户
            $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
            if (!$questionnaire) {
                throw new Exception("问卷不存在或无权查看", 404);
            }

            // 获取回答总数
            $stmt = $this->conn->prepare("
                SELECT COUNT(*) as total_answers
                FROM answers
                WHERE questionnaire_id = :questionnaire_id
            ");
            $stmt->execute([':questionnaire_id' => $questionnaireId]);
            $totalAnswers = (int)$stmt->fetchColumn();

            // 获取问题列表
            $stmt = $this->conn->prepare("
                SELECT id, type, content, options
                FROM questions
                WHERE questionnaire_id = :questionnaire_id
                ORDER BY sort_order ASC
            ");
            $stmt->execute([':questionnaire_id' => $questionnaireId]);
            $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 获取每个问题的回答统计
            $questionStats = [];
            foreach ($questions as $question) {
                if ($question['type'] === 'choice') {
                    // 选择题统计每个选项的选择次数
                    $options = json_decode($question['options'], true);
                    $optionStats = [];
                    
                    foreach ($options as $optionId => $optionText) {
                        $stmt = $this->conn->prepare("
                            SELECT COUNT(*) 
                            FROM answer_details
                            WHERE question_id = :question_id 
                            AND answer_content = :option_id
                        ");
                        $stmt->execute([
                            ':question_id' => $question['id'],
                            ':option_id' => $optionId
                        ]);
                        $count = (int)$stmt->fetchColumn();
                        
                        $optionStats[] = [
                            'option_id' => $optionId,
                            'option_text' => $optionText,
                            'count' => $count,
                            'percentage' => $totalAnswers > 0 ? round($count / $totalAnswers * 100, 2) : 0
                        ];
                    }
                    
                    $questionStats[] = [
                        'question_id' => $question['id'],
                        'question_text' => $question['content'],
                        'type' => 'choice',
                        'stats' => $optionStats
                    ];
                } else {
                    // 填空题只返回回答数量
                    $stmt = $this->conn->prepare("
                        SELECT COUNT(*) 
                        FROM answer_details
                        WHERE question_id = :question_id
                    ");
                    $stmt->execute([':question_id' => $question['id']]);
                    $count = (int)$stmt->fetchColumn();
                    
                    $questionStats[] = [
                        'question_id' => $question['id'],
                        'question_text' => $question['content'],
                        'type' => 'text',
                        'count' => $count
                    ];
                }
            }

            // 返回结果
            echo json_encode([
                'code' => 200,
                'data' => [
                    'total_answers' => $totalAnswers,
                    'questions' => $questionStats
                ]
            ]);

        } catch (Exception $e) {
            throw $e;
        }
    }

   /**
 * 提交问卷回答（POST方法）
 */
public function submit(): void {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        if ($input === null) {
            throw new Exception("无效的JSON数据", 400);
        }

        if (empty($input['id'])) {
            throw new Exception("缺少问卷ID参数", 400);
        }

        $questionnaireId = filter_var($input['id'], FILTER_VALIDATE_INT);
        if ($questionnaireId === false || $questionnaireId <= 0) {
            throw new Exception("问卷ID必须是正整数", 400);
        }

        // 检查问卷是否存在且已发布
        $stmt = $this->conn->prepare("
            SELECT id, status 
            FROM questionnaires 
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $questionnaireId]);
        $questionnaire = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$questionnaire) {
            throw new Exception("问卷不存在", 404);
        }

        if ($questionnaire['status'] !== 'published') {
            throw new Exception("问卷未发布或已关闭", 400);
        }

        // 检查问题是否都回答了
        $stmt = $this->conn->prepare("
            SELECT id, content, type, is_required, options
            FROM questions
            WHERE questionnaire_id = :questionnaire_id
            ORDER BY sort_order ASC
        ");
        $stmt->execute([':questionnaire_id' => $questionnaireId]);
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 验证回答数据
        $errors = [];
        foreach ($questions as $question) {
            $questionId = $question['id'];
            
            if ($question['is_required'] && !isset($input['answers'][$questionId])) {
                $errors[] = "问题 '{$question['content']}' 必须回答";
                continue;
            }
            
            if (isset($input['answers'][$questionId])) {
                $answer = $input['answers'][$questionId];
                
                if ($question['type'] === 'choice') {
                    // 验证选择题选项是否有效
                    $options = json_decode($question['options'], true);
                    if (is_array($options) && !array_key_exists($answer, $options)) {
                        $errors[] = "问题 '{$question['content']}' 的选择无效";
                    }
                } else {
                    // 验证填空题内容是否为空
                    if (empty(trim($answer))) {
                        $errors[] = "问题 '{$question['content']}' 的回答不能为空";
                    }
                }
            }
        }

        if (!empty($errors)) {
            throw new Exception(implode("; ", $errors), 400);
        }

        // 开始事务
        $this->conn->beginTransaction();

        try {
            // 创建回答记录
            $stmt = $this->conn->prepare("
                INSERT INTO answers (
                    questionnaire_id, respondent_ip, respondent_info, created_at
                ) VALUES (
                    :questionnaire_id, :ip, :info, NOW()
                )
            ");
            
            $ip = $_SERVER['REMOTE_ADDR'] ?? '';
            $respondentInfo = json_encode([
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'referer' => $_SERVER['HTTP_REFERER'] ?? ''
            ]);
            
            $stmt->execute([
                ':questionnaire_id' => $questionnaireId,
                ':ip' => $ip,
                ':info' => $respondentInfo
            ]);
            $answerId = $this->conn->lastInsertId();

            // 保存每个问题的回答
            foreach ($questions as $question) {
                $questionId = $question['id'];
                
                if (isset($input['answers'][$questionId])) {
                    $answer = $input['answers'][$questionId];
                    
                    // 如果是多选题，将数组转为逗号分隔的字符串
                    if ($question['type'] === 'check' && is_array($answer)) {
                        $answer = implode(',', $answer);
                    }
                    
                    $stmt = $this->conn->prepare("
                        INSERT INTO answer_details (
                            answer_id, question_id, answer_content
                        ) VALUES (
                            :answer_id, :question_id, :answer_content
                        )
                    ");
                    $stmt->execute([
                        ':answer_id' => $answerId,
                        ':question_id' => $questionId,
                        ':answer_content' => $answer
                    ]);
                }
            }

            $this->conn->commit();

            echo json_encode([
                'code' => 200,
                'msg' => '问卷提交成功'
            ]);

        } catch (Exception $e) {
            $this->conn->rollBack();
            throw new Exception("提交问卷失败: " . $e->getMessage(), 500);
        }

    } catch (Exception $e) {
        throw $e;
    }
}
/**
 * 复制问卷（支持自定义标题）
 */
public function copy(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if ($input === null) {
            throw new Exception("无效的JSON数据", 400);
        }

        if (empty($input['id'])) {
            throw new Exception("缺少问卷ID参数", 400);
        }

        $questionnaireId = filter_var($input['id'], FILTER_VALIDATE_INT);
        if ($questionnaireId === false || $questionnaireId <= 0) {
            throw new Exception("问卷ID必须是正整数", 400);
        }

        // 检查原问卷是否存在且属于当前用户
        $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
        if (!$questionnaire) {
            throw new Exception("问卷不存在或无权操作", 404);
        }

        // 确定新问卷标题
        $newTitle = $input['title'] ?? ($questionnaire['title'] . ' (副本)');

        // 开始事务
        $this->conn->beginTransaction();

        try {
            // 创建新问卷
            $stmt = $this->conn->prepare("
                INSERT INTO questionnaires (
                    user_id, title, description, status, is_template, created_at, updated_at
                ) VALUES (
                    :user_id, :title, :description, 'draft', 0, NOW(), NOW()
                )
            ");
            
            $stmt->execute([
                ':user_id' => $userId,
                ':title' => $newTitle,
                ':description' => $questionnaire['description']
            ]);
            $newQuestionnaireId = $this->conn->lastInsertId();

            // 复制问题
            $stmt = $this->conn->prepare("
                INSERT INTO questions (
                    questionnaire_id, type, content, is_required, sort_order, options, created_at
                )
                SELECT 
                    :new_questionnaire_id, type, content, is_required, sort_order, options, NOW()
                FROM questions
                WHERE questionnaire_id = :original_id
            ");
            $stmt->execute([
                ':new_questionnaire_id' => $newQuestionnaireId,
                ':original_id' => $questionnaireId
            ]);

            $this->conn->commit();

            echo json_encode([
                'code' => 200,
                'msg' => '问卷复制成功',
                'data' => [
                    'id' => $newQuestionnaireId,
                    'title' => $newTitle
                ]
            ]);

        } catch (Exception $e) {
            $this->conn->rollBack();
            throw new Exception("复制问卷失败: " . $e->getMessage(), 500);
        }

    } catch (Exception $e) {
        throw $e;
    }
}
/**
 * 重命名问卷
 */
public function rename(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $input = json_decode(file_get_contents('php://input'), true);
        if ($input === null) {
            throw new Exception("无效的JSON数据", 400);
        }

        // 验证必填字段
        if (empty($input['id'])) {
            throw new Exception("缺少问卷ID", 400);
        }
        if (empty($input['title'])) {
            throw new Exception("问卷标题不能为空", 400);
        }

        $questionnaireId = filter_var($input['id'], FILTER_VALIDATE_INT);
        if ($questionnaireId === false || $questionnaireId <= 0) {
            throw new Exception("问卷ID必须是正整数", 400);
        }

        // 检查问卷是否存在且属于当前用户
        $questionnaire = $this->getQuestionnaire($questionnaireId, $userId);
        if (!$questionnaire) {
            throw new Exception("问卷不存在或无权操作", 404);
        }

        // 更新标题
        $stmt = $this->conn->prepare("
            UPDATE questionnaires 
            SET title = :title, updated_at = NOW()
            WHERE id = :id AND user_id = :user_id
        ");
        $stmt->execute([
            ':title' => $input['title'],
            ':id' => $questionnaireId,
            ':user_id' => $userId
        ]);

        echo json_encode([
            'code' => 200,
            'msg' => '问卷重命名成功',
            'data' => [
                'id' => $questionnaireId,
                'new_title' => $input['title']
            ]
        ]);

    } catch (Exception $e) {
        throw $e;
    }
}
    /**
     * 获取问卷详情（内部方法）
     */
    private function getQuestionnaire(int $id, int $userId): ?array {
        $stmt = $this->conn->prepare("
            SELECT 
                id, title, description, status, 
                created_at, updated_at,
                (SELECT COUNT(*) FROM answers WHERE questionnaire_id = :id) as answer_count
            FROM questionnaires
            WHERE id = :id AND (user_id = :user_id OR is_template = 1)
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $id,
            ':user_id' => $userId
        ]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}